import { useState } from "react";
import { useTheme } from "@/hooks/useTheme";
import { Empty } from "@/components/Empty";
import { motion } from "framer-motion";
import { toast } from "sonner";

// 定义视频数据类型
interface VideoData {
  id: string;
  title: string;
  thumbnail: string;
  duration: string;
  views: number;
  likes: number;
  author: {
    name: string;
    avatar: string;
  };
  createdAt: string;
  isHunyuanGenerated?: boolean; // 标记是否由HunyuanVideo生成
}

// Mock视频数据
const mockVideos: VideoData[] = [
  {
    id: "1",
    title: "城市日落延时摄影 - AI生成",
    thumbnail: "https://space.coze.cn/api/coze_space/gen_image?image_size=landscape_16_9&prompt=city%20sunset%20timelapse%204k%20ultra%20hd&sign=fcf9eebcf7aa21161885060f67b24e48",
    duration: "01:24",
    views: 1254,
    likes: 89,
    author: {
      name: "创意工作室",
      avatar: "https://space.coze.cn/api/coze_space/gen_image?image_size=square&prompt=studio%20logo&sign=3789c275b830522e469131788d601f0a"
    },
    createdAt: "2025-11-17",
    isHunyuanGenerated: true
  },
  {
    id: "2",
    title: "海底世界探索 - 360度环绕运镜",
    thumbnail: "https://space.coze.cn/api/coze_space/gen_image?image_size=landscape_16_9&prompt=underwater%20world%20marine%20life%20coral%20reef&sign=9b95dbed5fd48f5c78c849e108a2b7bf",
    duration: "02:05",
    views: 3421,
    likes: 217,
    author: {
      name: "海洋探索者",
      avatar: "https://space.coze.cn/api/coze_space/gen_image?image_size=square&prompt=diver%20avatar&sign=c7cecf134284c305d5e35414b0e09237"
    },
    createdAt: "2025-11-16",
    isHunyuanGenerated: true
  },
  {
    id: "3",
    title: "太空漫步 - 科幻风格短片",
    thumbnail: "https://space.coze.cn/api/coze_space/gen_image?image_size=landscape_16_9&prompt=astronaut%20spacewalk%20science%20fiction&sign=81890f0d0fd5a01f949070ee5319309f",
    duration: "03:12",
    views: 5678,
    likes: 456,
    author: {
      name: "星际创意",
      avatar: "https://space.coze.cn/api/coze_space/gen_image?image_size=square&prompt=space%20logo&sign=0474f4c39df47d2aba39ff3051f99344"
    },
    createdAt: "2025-11-15",
    isHunyuanGenerated: true
  },
  {
    id: "4",
    title: "森林探险 - 自然纪录片风格",
    thumbnail: "https://space.coze.cn/api/coze_space/gen_image?image_size=landscape_16_9&prompt=forest%20adventure%20wildlife%20documentary&sign=246101bfaa9c854c8b5e0d6860defed3",
    duration: "01:48",
    views: 2345,
    likes: 178,
    author: {
      name: "自然之声",
      avatar: "https://space.coze.cn/api/coze_space/gen_image?image_size=square&prompt=tree%20logo&sign=0449beb61644d364d4b5d80f77743d5e"
    },
    createdAt: "2025-11-14",
    isHunyuanGenerated: true
  },
  {
    id: "5",
    title: "未来城市 - 概念设计演示",
    thumbnail: "https://space.coze.cn/api/coze_space/gen_image?image_size=landscape_16_9&prompt=future%20city%20floating%20buildings%20neon%20lights&sign=2b3c1e12da117135357aa953137a58e8",
    duration: "02:30",
    views: 4567,
    likes: 321,
    author: {
      name: "未来建筑",
      avatar: "https://space.coze.cn/api/coze_space/gen_image?image_size=square&prompt=architecture%20logo&sign=9e9043b2ce316ce7aa793a6d346e8c42"
    },
    createdAt: "2025-11-13",
    isHunyuanGenerated: true
  },
  {
    id: "6",
    title: "宇宙奥秘 - 星系旅行",
    thumbnail: "https://space.coze.cn/api/coze_space/gen_image?image_size=landscape_16_9&prompt=galaxy%20space%20travel%20stars%20nebulas&sign=c766e6aaaa86786e659608ce65a12314",
    duration: "04:15",
    views: 7890,
    likes: 654,
    author: {
      name: "天文探索",
      avatar: "https://space.coze.cn/api/coze_space/gen_image?image_size=square&prompt=planet%20logo&sign=9d054c032007398fe72f977e65165b6a"
    },
    createdAt: "2025-11-12",
    isHunyuanGenerated: true
  }
];

const Dashboard = () => {
  const { isDark } = useTheme();
  const [selectedCategory, setSelectedCategory] = useState("all");
  const [searchQuery, setSearchQuery] = useState("");
  const [videos, setVideos] = useState<VideoData[]>(mockVideos);
  const [isLoading, setIsLoading] = useState(false);

  // 过滤视频
  const filteredVideos = videos.filter(video => {
    const matchesSearch = video.title.toLowerCase().includes(searchQuery.toLowerCase());
    
    // 分类过滤逻辑
    if (selectedCategory === "all") return matchesSearch;
    if (selectedCategory === "popular") return matchesSearch && video.views > 3000;
    if (selectedCategory === "latest") {
      const videoDate = new Date(video.createdAt);
      const threeDaysAgo = new Date();
      threeDaysAgo.setDate(threeDaysAgo.getDate() - 3);
      return matchesSearch && videoDate >= threeDaysAgo;
    }
    
    return matchesSearch;
  });

  // 分类标签
  const categories = [
    { id: "all", name: "全部" },
    { id: "popular", name: "热门" },
    { id: "latest", name: "最新" },
    { id: "animation", name: "动画" },
    { id: "documentary", name: "纪录片" },
    { id: "scifi", name: "科幻" }
  ];

  // 格式化数字
  const formatNumber = (num: number): string => {
    if (num >= 1000) {
      return (num / 1000).toFixed(1) + "k";
    }
    return num.toString();
  };

  // 加载更多视频
  const loadMoreVideos = () => {
    setIsLoading(true);
    
    // 模拟加载更多视频的异步操作
    setTimeout(() => {
      // 这里只是复制现有视频作为演示，实际应用中应该从服务器获取
      setVideos(prev => [...prev, ...mockVideos.map(video => ({ 
        ...video, 
        id: video.id + Math.random().toString(36).substr(2, 9) // 生成新的ID
      }))]);
      setIsLoading(false);
      toast.success("已加载更多视频");
    }, 1000);
  };

  // 动画变体
  const containerVariants = {
    hidden: { opacity: 0 },
    visible: {
      opacity: 1,
      transition: {
        staggerChildren: 0.1
      }
    }
  };

  const itemVariants = {
    hidden: { opacity: 0, y: 20 },
    visible: {
      opacity: 1,
      y: 0,
      transition: {
        duration: 0.5
      }
    }
  };

  return (
    <div className={`min-h-screen ${isDark ? 'text-white' : 'text-slate-900'}`}>
      {/* 背景装饰 */}
      <div className={`fixed inset-0 -z-10 opacity-10 ${isDark ? 'bg-gradient-dark-ai' : 'bg-gradient-ai'}`}></div>
      
      <div className="container mx-auto max-w-7xl">
        {/* 页面标题 */}
        <div className="mb-8">
          <h1 className="text-3xl md:text-4xl font-bold mb-2">AI视频画廊</h1>
          <p className={`${isDark ? 'text-slate-400' : 'text-slate-600'}`}>
            探索社区创作的精彩AI视频作品，全部由HunyuanVideo模型生成
          </p>
        </div>

        {/* 搜索和分类 */}
        <div className="mb-8 flex flex-col md:flex-row gap-4 md:items-center justify-between">
          <div className={`relative flex-1 max-w-md ${isDark ? 'bg-slate-800' : 'bg-white'} rounded-full shadow-md`}>
            <input
              type="text"
              placeholder="搜索视频..."
              className={`w-full pl-12 pr-4 py-3 rounded-full focus:outline-none focus:ring-2 focus:ring-indigo-500 ${isDark ? 'bg-transparent placeholder-slate-500' : 'placeholder-slate-400'}`}
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
            />
            <i className="fa-solid fa-search absolute left-4 top-1/2 transform -translate-y-1/2 text-slate-400"></i>
          </div>
          
          <div className="flex overflow-x-auto gap-2 pb-2 md:pb-0">
            {categories.map(category => (
              <button
                key={category.id}
                className={`px-4 py-2 rounded-full whitespace-nowrap transition-all duration-300 ${
                  selectedCategory === category.id 
                    ? 'bg-indigo-600 text-white shadow-lg' 
                    : `${isDark ? 'bg-slate-800 hover:bg-slate-700' : 'bg-white hover:bg-slate-100'} shadow`
                }`}
                onClick={() => setSelectedCategory(category.id)}
              >
                {category.name}
              </button>
            ))}
          </div>
        </div>

        {/* 视频网格 */}
        {filteredVideos.length > 0 ? (
          <motion.div 
            className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6"
            variants={containerVariants}
            initial="hidden"
            animate="visible"
          >
            {filteredVideos.map(video => (
              <motion.div
                key={video.id}
                variants={itemVariants}
                className={`rounded-xl overflow-hidden ${isDark ? 'bg-slate-800' : 'bg-white'} shadow-lg video-card-hover`}
              >
                {/* 视频缩略图 */}
                <div className="relative aspect-video overflow-hidden">
                  <img 
                    src={video.thumbnail} 
                    alt={video.title}
                    className="w-full h-full object-cover transition-transform duration-500 hover:scale-110"
                  />
                  <div className="absolute bottom-2 right-2 bg-black/70 text-white text-xs px-1.5 py-0.5 rounded">
                    {video.duration}
                  </div>
                  
                  {/* HunyuanVideo生成标记 */}
                  {video.isHunyuanGenerated && (
                    <div className="absolute top-2 left-2 bg-gradient-to-r from-indigo-600 to-purple-600 text-white text-xs px-2 py-1 rounded-full">
                      <i className="fa-solid fa-robot mr-1"></i>Hunyuan生成
                    </div>
                  )}
                  
                  {/* 播放按钮覆盖层 */}
                  <div className="absolute inset-0 bg-black/30 opacity-0 hover:opacity-100 flex items-center justify-center transition-opacity duration-300">
                    <button className="w-16 h-16 rounded-full bg-white/20 backdrop-blur-sm flex items-center justify-center transform hover:scale-110 transition-transform duration-300">
                      <i className="fa-solid fa-play text-white text-xl"></i>
                    </button>
                  </div>
                </div>
                
                {/* 视频信息 */}
                <div className="p-4">
                  <h3 className="font-semibold text-lg mb-2 line-clamp-1">{video.title}</h3>
                  
                  <div className="flex items-center justify-between mb-3">
                    <div className="flex items-center space-x-3">
                      <img 
                        src={video.author.avatar} 
                        alt={video.author.name}
                        className="w-6 h-6 rounded-full"
                      />
                      <span className={`text-sm ${isDark ? 'text-slate-400' : 'text-slate-600'}`}>
                        {video.author.name}
                      </span>
                    </div>
                    <span className={`text-sm ${isDark ? 'text-slate-400' : 'text-slate-600'}`}>
                      {video.createdAt}
                    </span>
                  </div>
                  
                  <div className="flex items-center space-x-4">
                    <div className="flex items-center space-x-1 text-sm">
                      <i className="fa-solid fa-eye text-slate-400"></i>
                      <span>{formatNumber(video.views)}</span>
                    </div>
                    <div className="flex items-center space-x-1 text-sm">
                      <i className="fa-solid fa-heart text-pink-500"></i>
                      <span>{formatNumber(video.likes)}</span>
                    </div>
                    <div className="ml-auto">
                      <button className={`p-1.5 rounded-full ${isDark ? 'hover:bg-slate-700' : 'hover:bg-slate-100'}`}>
                        <i className="fa-solid fa-ellipsis-vertical"></i>
                      </button>
                    </div>
                  </div>
                </div>
              </motion.div>
            ))}
          </motion.div>
        ) : (
          <Empty message="没有找到匹配的视频" />
        )}

        {/* 加载更多按钮 */}
        {filteredVideos.length > 0 && (
          <div className="mt-12 text-center">
            <button 
              className={`px-8 py-3 rounded-full ${isDark ? 'bg-slate-800 hover:bg-slate-700' : 'bg-white hover:bg-slate-100'} shadow transition-colors duration-300`}
              onClick={loadMoreVideos}
              disabled={isLoading}
            >
              {isLoading ? (
                <>
                  <i className="fa-solid fa-spinner fa-spin mr-2"></i>
                  加载中...
                </>
              ) : (
                <>
                  加载更多
                  <i className="fa-solid fa-chevron-down ml-2"></i>
                </>
              )}
            </button>
          </div>
        )}
      </div>
    </div>
  );
};

export default Dashboard;